<?php

class UsermanagerController extends SilkControllerBase {
	
	public function index($params) {
		self::buildNavigation();
	}
	
	public function manageUsers($params) {
		self::buildNavigation();
		$this->set("users", orm("user")->find_all(array("conditions" => array("status_id > 0"))));
	}	
	
	public function newUser($params) {
		$config = load_config();
		self::buildNavigation();
		
		if( isset( $params["input"] )) {
			if( isset( $config["default_usertype"] )) {
				$user = new $config["default_usertype"];
			} else {
				$user = new SilkUser();
			}
			$user->update_parameters($params);
			$user->status_id = 1;
				
			if( $params["pass1"] == $params["pass2"] && $params["pass1"] != "") {
				$user->set_password( $params["pass1"] );
				$user->save();
				$this->flash = "New user added";

				redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageUsers")));
			} else {
				$this->set("message", "Passwords don't match");
			}
		}
		
		if( empty( $user )) {
			if( isset( $config["default_usertype"] )) {
				$user = new $config["default_usertype"];
			} else {
				$user = new SilkUser();
			}
		}
		$fields = array();
		$fields["password"]["visible"] = "none";
		$fields["last_login"]["visible"] = "none";
		$this->set("newUserForm", SilkForm::auto_form($user, array("fields" => $fields), array(), false, false, false));
	}
	
	public function editUser($params) {
		self::buildNavigation();
		if( isset($params["input"]) ) {
			$user = orm("SilkUser")->find_by_id($params["id"]);
			$user->update_parameters($params);
			$user->save();
				
			// delete all groups for this user
			// done outside of isset $params[groups] in case there aren't any groups to set
			db()->Execute("DELETE FROM ". db_prefix() . "user_groups WHERE user_id = $user->id");
				
			if( isset( $params["groups"] )) {
				$date = db()->DBTimeStamp(time());
				foreach( $params["groups"] as $group_id ) {
					db()->Execute("INSERT INTO " . db_prefix() . "user_groups (user_id, group_id, create_date, modified_date) VALUES (?,?,{$date},{$date})", array($user->id, $group_id));
				}
			}
			$this->flash = "Saved user changes";
			redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageUsers")));
		}

		$user = orm("SilkUser")->find_by_id($params["id"]);
		$this->set("groups",orm("group")->find_all());
		$this->set("userGroups", $user->groups);
		
		$fields = array();
		$fields["password"]["visible"] = "none";
		$this->set("userForm", SilkForm::auto_form($user, array("fields" => $fields), null, false, false, false));
	}
	
	public function deleteUser($params) {
		$user = orm("user")->find_by_id($params["id"]);
		$user->status_id = 0;
		$user->save();
		$this->flash = $user->first_name . " " . $user->last_name . " has been deleted";
		redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageUsers")));
	}

	public function manageGroups($params) {
		self::buildNavigation();
		$this->set("groups", orm("group")->find_all(array("conditions" => array("status_id > 0"))));
	}

	public function newGroup($params) {
		self::buildNavigation();
		if( isset( $params["input"])) {
			$group = new SilkGroup();
			$group->update_parameters($params);
			$group->save();
			
			redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageGroups", "msg" => "New group created")));
		}
		
		if( empty( $group )) {
			$group = new SilkGroup();
		}
		$this->set("newGroupForm", SilkForm::auto_form($group, array(), array(), true, true, true));
	}

	public function editGroup($params) {
		self::buildNavigation();
		if( isset($params["input"]) ) {
			$group = orm("group")->find_by_id($params["id"]);
			$group->update_parameters($params);
			$group->save();

			// delete all users from this group
			// has to be outside the isset $params["users"] in case there are no users
			db()->Execute("DELETE FROM ". db_prefix() . "user_groups WHERE group_id = $group->id");
			
			if( isset( $params["users"] )) {
				$date = db()->DBTimeStamp(time());
				foreach( $params["users"] as $user_id ) {
					db()->Execute("INSERT INTO " . db_prefix() . "user_groups (user_id, group_id, create_date, modified_date) VALUES (?,?,{$date},{$date})", array($user_id, $group->id));
				}
			}
			$this->flash = "Saved changes";
			redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageGroups")));
		}
		$group = orm("group")->find_by_id($params["id"]);
		$this->set("users", orm("user")->find_all());
		$this->set("groupUsers", $group->users);
		$fields = array();
		$this->set("groupForm", SilkForm::auto_form($group, array("fields" => $fields), null, false, false, false));
	}
	
	public function deleteGroup($params) {
		$group = orm("group")->find_by_id($params["id"]);
		$group->status_id = 0;
		$group->save();
		$this->flash = $group->name . " has been deleted";
		redirect(SilkResponse::create_url(array("controller" => "usermanager", "action" => "manageGroups")));
	}
	
	public function buildNavigation() {
		$links = array();
		$links["Manage Users"] = SilkResponse::create_url(array("controller" => "usermanager",
																"action" => "manageUsers"));
		$links["Manage Groups"] = SilkResponse::create_url(array(	"controller" => "usermanager",
																	"action" => "manageGroups"));
		if( class_exists("MenuManagerController")) {
			$this->set("subMenu", MenuManagerController::auto_menu(array("menuItems" => $links, "subMenu" => true)));
		}
	}
	
	function login($params) {
		if(!isset($params["div_id"])) { $params["div_id"] = "leftcolumn"; }
		if(!isset($params["redirect"])) {
			$params["redirect"] = $_SERVER["HTTP_REFERER"];
		}
		$this->set("redirect",$params["redirect"]);
		$this->set("div_id","leftcolumn");
		if(!SilkUserSession::get_current_user()) {
		  	if( isset( $params["login"] ) ) {
			    $user_session = new SilkUserSession($params['login']);
			    if ($user_session->login())
			    {
			    	$user = orm("SilkUser")->find_by_id($_SESSION["silk_user"]->params["id"]);
			    	$user->last_login = new SilkDateTime();
			    	
			    	if(!$user->save()) {
			    		echo "Error saving user record<br />"; die;
			    	}
			    	$this->flash = "Login successful";
			    	redirect($params["redirect"]);
			    } else {
			    	$this->set("loginFail", "Login failed, please try again");
			    }
		  	}
		} else {
			$this->set("loggedInMessage", "Logged in as: ". $_SESSION["silk_user"]->params["username"]);
		}
	  	
	  	$registerLink = SilkResponse::create_url(array(	"component" => "usermanager",
	  													"controller" => "usermanager",
	  													"action" => "register"
	  													));
	  	$this->set("registerLink", $registerLink);

	}
	
	function logout($params) {
  		SilkUserSession::logout();
  		$this->flash = "You have been logged out";
  		if(isset($params["redirect"])) {
	  		redirect($params["redirect"]);
  		} else {
  			$config = load_config();
  			redirect($config["homepage"]);
  		}
	}
	
	function register($params) {
		if(isset($params["more_params"])) {
			$params = array_merge($params, $params["more_params"]);
			unset($params["more_params"]);
		}
		$config = load_config();
		if(!isset($params["div_id"])) { $this->set("div_id", "leftcolumn"); }
		if(!isset($params["redirect"])) {
			$params["redirect"] = SilkRequest::get_requested_page();
			$params["redirect"] = join_path(SilkRequest::get_calculated_url_base(true), $this->get_component_name());
		}
		
		if( isset($params["input"])) {
			if( isset( $config["default_usertype"] )) {
				$reguser = new $config["default_usertype"];
			} else {
				$reguser = new SilkUser();
			}
			if( isset($params["date_of_birth_year"] )) {
				$params["date_of_birth"] = $params["date_of_birth_year"] . "-" . $params["date_of_birth_month"] . "-" . $params["date_of_birth_day"];
			}
			$reguser->update_parameters($params);
			$reguser->set_password($params["password"]);
			$reguser->status_id = 1;
			
			if( $reguser->save()) {
				$this->set("reguser", SilkForm::data_table($reguser));
				$params["register"]["username"] = $params["username"];
				$params["register"]["password"] = $params["password"];
				
				$user_session = new SilkUserSession($params["register"]);
				
				if($user_session->login()) {
					$user = orm("SilkUser")->find_by_id($_SESSION["silk_user"]->params["id"]);
			    	$user->last_login = new SilkDateTime();
			    	$user->save();
			    	redirect($params["redirect"]);
				} else {
					//TODO: Set up a flash here and redirect somewhere
					echo "Login failed";
				}
				return;
			} else {
				$this->set("reguser", $reguser);
			}
		}
		
		if( !isset( $params["fields"] )) {
			$params["fields"] = array();
		}
		
		if( isset( $config["default_usertype"] )) {
			$user = new $config["default_usertype"];
		} else {
			$user = new SilkUser();
		}
		
		$user->fill_object($params, $user);
		$regform = SilkForm::auto_form($user, array("fields" => $params["fields"]), null, true, true, true);
		$this->set("regform", $regform);
	}
	
	public function registerStepTwo( $params ) {
		
	}
	
	function showUsers($params) {
		$users = orm("silk_user")->find_all(array("order" => "username DESC"));
		$this->set("users", $users);
	}
	
	function testLogin($params) {
		echo "Current user: " . SilkUserSession::get_current_user(). "<br />";
	}
}
?>